package com.yicong.ants.ui.video.adapter;

import static com.yicong.ants.utils.UIUtils.showToast;

import android.app.Activity;
import android.content.DialogInterface;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.cchao.simplelib.core.AndroidHelper;
import com.cchao.simplelib.core.CollectionHelper;
import com.cchao.simplelib.core.Logs;
import com.cchao.simplelib.core.Router;
import com.cchao.simplelib.core.RxBus;
import com.cchao.simplelib.core.RxHelper;
import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.ui.adapter.StatefulBindMultiQuickAdapter;
import com.cchao.simplelib.ui.interfaces.BaseView;
import com.cchao.simplelib.util.StringHelper;
import com.dueeeke.videoplayer.player.VideoView;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.kennyc.view.MultiStateView;
import com.kwad.sdk.api.KsDrawAd;
import com.yicong.ants.BR;
import com.yicong.ants.Constants;
import com.yicong.ants.R;
import com.yicong.ants.bean.base.ListRespBean;
import com.yicong.ants.bean.common.MultiItemWrapper;
import com.yicong.ants.bean.video.VideoListBean;
import com.yicong.ants.databinding.DialogVideoShareBinding;
import com.yicong.ants.manager.BusinessHelper;
import com.yicong.ants.manager.ConfigService;
import com.yicong.ants.manager.RouterHelper;
import com.yicong.ants.manager.UserManager;
import com.yicong.ants.manager.business.Dialogs;
import com.yicong.ants.manager.http.RetrofitHelper;
import com.yicong.ants.ui.video.CommentDialog;
import com.yicong.ants.ui.video.VideoProfileActivity;
import com.yicong.ants.ui.video.manager.OnViewPagerListener;
import com.yicong.ants.ui.video.manager.ViewPagerLayoutManager;
import com.yicong.ants.utils.L;
import com.yicong.ants.utils.VideoUtils;
import com.yicong.ants.utils.video.cache.PreloadManager;
import com.yicong.ants.view.video.VideoGiftListDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.disposables.CompositeDisposable;


/**
 * @author cch
 * @version 2021/4/16
 */
public class VideoListAdapter extends StatefulBindMultiQuickAdapter<MultiItemWrapper> {
    CompositeDisposable mDisposable;
    BaseView mBaseView;
    //    String mUid = UserManager.getUserId();//未登录时userbean为null，会蹦
    String mUserId = "";
    // type 区分 视频主页的喜欢和发布
    String mType = "";
    // mRecommend 0=系统推荐视频，1=推荐关注作者视频
    public int mRecommend = 0;
    // 如果有vid，说明是通过链接分享过来单一视频
    String mVid = "";
    Activity mContext;
    ViewPagerLayoutManager mViewPagerLayoutManager;
    public VideoView mVideoView;
    View mPreCover;
    View mCurCover;
    int mCurSelectPage = -1;

    public static final int NORMAL_VIDEO = 1;
    public static final int AD_VIDEO = 2;
//    public static final int KS_VIDEO = 3;

    @Override
    public Map<Integer, Integer> getTypeLayoutMap() {
        Map<Integer, Integer> map = new HashMap<>(8);
        map.put(NORMAL_VIDEO, R.layout.item_short_video);
        map.put(AD_VIDEO, R.layout.video_ad_item);
//        map.put(KS_VIDEO, R.layout.video_ks_draw_item);
        return map;
    }

    public VideoListAdapter(BaseView baseView, Activity context, CompositeDisposable disposable) {
        super(null);
//        super(R.layout.item_tiktok2);
        mDisposable = disposable;
        mContext = context;
        mBaseView = baseView;
        initVideoView();
        initEvent();
    }

    @Override
    public int getItemCount() {
        if (StringHelper.isNotEmpty(mVid)) {
            return 1;
        }
        return super.getItemCount();
    }

    private void initEvent() {
        mDisposable.add(RxBus.get().toObservable(event -> {
            switch (event.getCode()) {
                case Constants.Event.Video_Follow_Update:
                    for (int i = 0; i < getData().size(); i++) {
                        if (isAdVideo(i)) continue;
                        VideoListBean bean = (VideoListBean) getData().get(i).getObject();
                        if (BusinessHelper.mVideoFocus.containsKey(bean.getUid())
                                && BusinessHelper.mVideoFocus.get(bean.getUid()) != bean.is_focus()) {
                            bean.set_focus(BusinessHelper.mVideoFocus.get(bean.getUid()));
                            notifyItemChanged(i);
                        }
                    }
                    break;
                case Constants.Event.Video_Commit_Suc:
                    Map<String, String> params = new HashMap<>();
                    params.put("vid", event.getContent());
                    mDisposable.add(RetrofitHelper.getApis().getVideoDetail(params)
                            .compose(RxHelper.toMain())
                            .subscribe(respBean -> {
                                if (respBean.isCodeFail()) {
                                    showToast(respBean.getMsg());
                                    return;
                                }
                                List<MultiItemWrapper> wrapperList = getData();
                                for (int i = 0; i < wrapperList.size(); i++) {
                                    if (isAdVideo(i)) continue;
                                    MultiItemWrapper object = wrapperList.get(i);
                                    VideoListBean bean = (VideoListBean) object.getObject();
                                    if (!bean.getVid().equalsIgnoreCase(event.getContent())) {
                                        continue;
                                    }
                                    bean.setComment_qty(respBean.getData().getComment_qty());
                                    bean.setLike_qty(respBean.getData().getLike_qty());
                                    if (mCurSelectPage == wrapperList.indexOf(object)) {
                                        View view = getViewByPosition(mCurSelectPage, R.id.tv_comment);
                                        if (view != null) {
                                            ((TextView) view).setText(bean.getComment_qty_text());
                                        }
                                    }
                                }
                            }, RxHelper.getErrorTextConsumer(mBaseView)));
                    break;
            }
        }));
    }

    void toggleVisibleView(View view, boolean t) {
        Logs.d("toggleVisibleView " + view);
        if (view == null) {
            return;
        }
        UiHelper.setVisibleElseGone(view, t);
    }

    private void initVideoView() {
        mVideoView = new VideoView(mContext);
        mVideoView.setLooping(true);
        mVideoView.setOnClickListener(v -> VideoUtils.videoStartOrPause(mVideoView));
        mVideoView.setOnStateChangeListener(new VideoView.SimpleOnStateChangeListener() {
            @Override
            public void onPlayStateChanged(int playState) {
                switch (playState) {
                    case VideoView.STATE_IDLE:
                        Logs.i("STATE_IDLE " + hashCode());
                        toggleVisibleView(mCurCover, true);
                        toggleVisibleView(getViewByPosition(mCurSelectPage, R.id.pause), false);
                        break;
                    case VideoView.STATE_PLAYING:
                        Logs.i("STATE_PLAYING " + hashCode());
                        toggleVisibleView(mCurCover, false);
                        toggleVisibleView(getViewByPosition(mCurSelectPage, R.id.pause), false);
                        break;
                    case VideoView.STATE_PAUSED:
                        Logs.i("STATE_PAUSED " + hashCode());
                        toggleVisibleView(getViewByPosition(mCurSelectPage, R.id.pause), true);
                        break;
                    case VideoView.STATE_PREPARED:
                        toggleVisibleView(mCurCover, true);
                        Logs.i("STATE_PREPARED " + hashCode());
                        break;
                    case VideoView.STATE_ERROR:
                        Logs.i("STATE_ERROR " + hashCode());
                        mBaseView.showToast("播放失败");
//                        Toast.makeText(getContext(), R.string.dkplayer_error_message, Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    public VideoListAdapter setUserId(String userId) {
        mUserId = userId;
        return this;
    }

    public VideoListAdapter setType(String type) {
        mType = type;
        return this;
    }

    public VideoListAdapter setVid(String vid) {
        mVid = vid;
        return this;
    }

    public View getCurCover() {
        if (mVideoView == null) {
            return null;
        }

        if (mVideoView.getParent() == null) {
            return null;
        }

        ViewParent parent = mVideoView.getParent().getParent();
        if (parent instanceof ViewGroup) {
            ((ViewGroup) parent).findViewById(R.id.cover);
        }
        return null;
    }

    @Override
    public void bindToRecyclerView(RecyclerView recyclerView) {
        super.bindToRecyclerView(recyclerView);
        recyclerView.setItemViewCacheSize(5);
        recyclerView.setHasFixedSize(true);
//        recyclerView.getRecycledViewPool().setMaxRecycledViews(1, 5);
    }

    public ViewPagerLayoutManager getViewPagerLayoutManager() {
        if (mViewPagerLayoutManager != null) {
            return mViewPagerLayoutManager;
        }
        mViewPagerLayoutManager = new ViewPagerLayoutManager(mContext, OrientationHelper.VERTICAL);
        mViewPagerLayoutManager.setOnViewPagerListener(new OnViewPagerListener() {
            @Override
            public void onInitComplete() {
                //自动播放第index条
                startPlay(0);
            }

            @Override
            public void onPageRelease(boolean isNext, int position) {

            }

            @Override
            public void onPageSelected(int position, boolean isBottom) {
//                if (mCurPos == position) {
//                    return;
//                }
                Logs.d("VideoListAdapter onPageSelected" + position);
                startPlay(position);
                preLoadNext(position + 1);
                preLoadNext(position + 2);

                if (mCurSelectPage != position) {
                    toggleVisibleView(mPreCover, true);
                }
//                toggleVisibleView(getViewByPosition(position - 1, R.id.cover), true);
//                toggleVisibleView(getViewByPosition(position + 1, R.id.cover), true);

//                toggleVisibleView(getViewByPosition(position - 1, R.id.pause), false);
//                toggleVisibleView(getViewByPosition(position + 1, R.id.pause), false);
            }
        });
        return mViewPagerLayoutManager;
    }

    void startPlay(int position) {
        if (getItem(position) != null
                && getItem(position).getItemType() != NORMAL_VIDEO) {
            return;
        }
        startPlay(position, mViewPagerLayoutManager.findViewByPosition(position));
    }

    void startPlay(int position, View itemView) {
        if (CollectionHelper.isEmpty(getData()) || getData().size() < position + 1) {
            return;
        }
        if (isAdVideo(position)) {
            mCurSelectPage = position;
            return;
        }

        if (itemView == null) {
            return;
        }

        if (mCurSelectPage == position) {
            return;
        }

        mVideoView.release();
        VideoUtils.removeViewFormParent(mVideoView);
        VideoListBean item = (VideoListBean) getData().get(position).getObject();
        String playUrl = PreloadManager.getInstance(mContext).getPlayUrl(item.getUrl());
        L.i("VideoListFragment", "position: " + position + ",Title: " + item.getTitle() + "\nplayUrl: " + playUrl + "\n itemUrl(): " + item.getUrl());
        mVideoView.setUrl(playUrl);
        FrameLayout playerContainer = itemView.findViewById(R.id.player_container);
        playerContainer.addView(mVideoView, 0);
        mVideoView.start();

        mCurSelectPage = position;
        mPreCover = mCurCover;
        mCurCover = itemView.findViewById(R.id.cover);
        BusinessHelper.saveVid(item.getVid());
    }

    void preLoadNext(int position) {
        if (CollectionHelper.isEmpty(getData()) || getData().size() < position + 1) {
            return;
        }
        if (isAdVideo(position)) {
            return;
        }
        PreloadManager.getInstance(mContext).addPreloadTask(((VideoListBean) getData().get(position).getObject()).getUrl(), position);
    }

    private boolean isAdVideo(int position) {
        return getData().get(position).getItemType() == AD_VIDEO;
//        return getData().get(position).getItemType() == AD_VIDEO || getData().get(position).getItemType() == KS_VIDEO;
    }

    @Override
    protected void convert(DataBindViewHolder helper, MultiItemWrapper item) {
        Logs.d("VideoListAdapter convert " + helper.getAdapterPosition());
        switch (helper.getItemViewType()) {
            case NORMAL_VIDEO:
                showNormalVideo(helper, (VideoListBean) item.getObject());
                break;
            case AD_VIDEO:
                showKSAd(helper, (KsDrawAd) item.getObject());
                break;
//            case KS_VIDEO:
//                loadKsDraw(helper, item);
//                break;
        }
    }

    private void showNormalVideo(DataBindViewHolder helper, final VideoListBean item) {
        helper.getBinding().setVariable(BR.bean, item);
        if (mCurSelectPage != helper.getAdapterPosition()) {
            toggleVisibleView(helper.getView(R.id.cover), true);
        }

        helper.getBinding().setVariable(BR.click, (View.OnClickListener) view -> {
            switch (view.getId()) {
                case R.id.iv_header:
                case R.id.tv_nick_name:
                    Router.turnTo(mContext, VideoProfileActivity.class)
                            .putExtra(Constants.Extra.Video_isFocus, item.is_focus())
                            .putExtra(Constants.Extra.Uid, item.getUid())
                            .start();
                    break;

                case R.id.focus:
                    if (UserManager.notLogin()) {
                        UiHelper.showToast("请先登录");
                        return;
                    }

                    if (UserManager.getUserId().equals(item.getUid())) {
                        return;
                    }

                    Map<String, String> focusMap = new HashMap<>();
                    focusMap.put("author_uid", item.getUid());

                    mDisposable.add(RetrofitHelper.getApis().videoFocus(focusMap)
                            .compose(RxHelper.toMain())
                            .subscribe(respBean -> {
                                if (respBean.isCodeFail()) {
                                    UiHelper.showToast(respBean.getMsg());
                                    return;
                                }
                                item.set_focus(!item.is_focus());
                                UiHelper.setVisibleElseGone(view.findViewById(R.id.focus), !item.is_focus());
                                BusinessHelper.putFollow(item.getUid(), item.is_focus());
                            }, RxHelper.getHideProgressConsumer(mBaseView)));
                    break;

                case R.id.videoLike:
                    if (UserManager.notLogin()) {
                        UiHelper.showToast("请先登录");
                        return;
                    }

                    Map<String, String> map = new HashMap<>();
                    map.put("action", "0");
                    map.put("vid", item.getVid());

                    mDisposable.add(RetrofitHelper.getApis().videoLike(map)
                            .compose(RxHelper.toMain())
                            .subscribe(respBean -> {
                                if (respBean.isCodeFail()) {
                                    mBaseView.showToast(respBean.getMsg());
                                    return;
                                }

                                if (item.is_like()) {
                                    item.set_like(false);
                                    item.setLike_text(String.valueOf(item.getLike_qty() - 1));
                                    item.setLike_qty(item.getLike_qty() - 1);
                                } else {
                                    item.set_like(true);
                                    item.setLike_text(String.valueOf(item.getLike_qty() + 1));
                                    item.setLike_qty(item.getLike_qty() + 1);
                                }
                                item.update_like(view.findViewById(R.id.videoLike));

                            }, RxHelper.getHideProgressConsumer(mBaseView)));
                    break;
                case R.id.gift:
                    VideoGiftListDialog mVideoGiftListDialog = new VideoGiftListDialog(mContext, item.getVid(), mDisposable);
                    mVideoGiftListDialog.show();
                    break;

                case R.id.foreign_link_container:
                    if (StringHelper.isNotEmpty(item.getForeign_link())) {
                        RouterHelper.tryRoutePlatformUri(mContext, item.getForeign_link());
                    }
                    break;

                case R.id.tv_comment:
                    if (UserManager.notLogin()) {
                        return;
                    }

                    Runnable runnable = () -> {
                        if (Integer.parseInt(UserManager.getUserBean().getEnergy()) < 100) {
                            UiHelper.showToast("您的活跃度不够");
                            return;
                        }
                        new CommentDialog(mContext, mDisposable, item).show();
                    };

                    Dialogs.showDisclaimer(mContext, "评论说明"
                            , ConfigService.getConfig(ConfigService.tip_public_video_comment)
                            , Constants.Prefs.Video_Comment_Tip
                            , runnable);
                    break;

                case R.id.share:
                    BottomSheetDialog dialog = new BottomSheetDialog(mContext, R.style.VideoDialog);
                    DialogVideoShareBinding binding = DataBindingUtil.inflate(mLayoutInflater, R.layout.dialog_video_share, null, false);
                    binding.setMType(mType);
                    binding.setClick(v -> {
                        String link = "ants://platform/app?id=11070&vid=" + item.getVid();
                        switch (v.getId()) {
                            case R.id.close:
                                dialog.dismiss();
                                break;
                            case R.id.link:
                                String shareLink = "【复制内容，打开蚁丛旅游App即可查看】\n" + item.getTitle() + '\n' + link;
                                AndroidHelper.setClipboardData(shareLink, () -> {
                                    //
                                    Toast toast = Toast.makeText(mContext, "链接已复制", Toast.LENGTH_SHORT);
                                    toast.setGravity(Gravity.CENTER, 0, 0);
                                    toast.show();
                                });
                                break;
                            case R.id.wx:
                                BusinessHelper.shareAntLink(mContext, item.getTitle(), link);
                                break;
                            case R.id.qr_code:
                                Dialogs.showQrContent(mContext, item.getTitle(), link);
                                break;
                            case R.id.download:
                                if (BusinessHelper.mVideoDownloading) {
                                    showToast("视频正在下载中");
                                    return;
                                }
                                BusinessHelper.downloadVideo(item, mContext);
                                showToast("视频下载中");
                                break;
                            case R.id.del_video:
                                UiHelper.showConfirmActionDialog(mContext, "确认删除视频?", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        delVideo(item.getVid());
                                    }
                                });
                                break;
                        }
                        dialog.dismiss();
                    });
                    dialog.setContentView(binding.getRoot());
                    dialog.show();
                    break;
            }
        });
        Logs.d("VideoListAdapter mCurSelectPage " + mCurSelectPage);
        // page select 有滞后性
        if (mCurSelectPage == -1) {
            startPlay(helper.getAdapterPosition(), helper.itemView);
        }
    }

    //删除自己的视频
    private void delVideo(String mVid) {
        Map<String, String> map = new HashMap<>();
        map.put("vid", mVid);
        mDisposable.add(RetrofitHelper.getApis().delVideo(map)
                .compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    if (respBean.isCodeFail()){
                        mBaseView.showToast(respBean.getMsg());
                        return;
                    }
                    mBaseView.showToast(respBean.getMsg());
                    RxBus.get().postEvent(Constants.Event.Video_Del_Update);
                },RxHelper.getHideProgressConsumer(mBaseView)));
    }

    //视频页面ks广告展示
    private void showKSAd(DataBindViewHolder holder, KsDrawAd ksDrawAd) {
        ksDrawAd.setAdInteractionListener(new KsDrawAd.AdInteractionListener() {
            @Override
            public void onAdClicked() {
                //广告点击回调

            }

            @Override
            public void onAdShow() {
                //广告曝光回调
            }

            @Override
            public void onVideoPlayStart() {
                //广告视频开始播放
            }

            @Override
            public void onVideoPlayPause() {
                //广告视频暂停播放
            }

            @Override
            public void onVideoPlayResume() {
                //广告视频恢复播放
            }

            @Override
            public void onVideoPlayEnd() {
                //广告视频播放结束
            }

            @Override
            public void onVideoPlayError() {
                //广告视频播放出错
            }
        });

        View drawViewView = ksDrawAd.getDrawView(mContext);
        if (drawViewView != null && drawViewView.getParent() == null) {
            ViewGroup adContainer = holder.getView(R.id.container);
            adContainer.removeAllViews();
            adContainer.addView(drawViewView);
        }
    }

    @Override
    public void loadPageData(int page) {
        Map<String, String> params = new HashMap<>();
        params.put("page", String.valueOf(page));
        params.put("page_size", Constants.PAGE_SIZE_Str);
        params.put("type", String.valueOf(mType));
        params.put("recommend_type", String.valueOf(mRecommend));
        params.put("user_id", String.valueOf(mUserId));

        if (page == 1) {
            setViewState(MultiStateView.VIEW_STATE_LOADING);
        }

        Observable<ListRespBean<VideoListBean>> observable = RetrofitHelper.getApis().getVideoList(params);
        if (StringHelper.isNotEmpty(mType)) {
            observable = RetrofitHelper.getApis().getVideoHomeList(params);
        }

        mDisposable.add(observable.compose(RxHelper.toMain())
                .subscribe(respBean -> {
                    if (respBean.isCodeFail()) {
                        showToast(respBean.getMsg());
                        if (CollectionHelper.isEmpty(mData)) {
                            setViewState(MultiStateView.VIEW_STATE_EMPTY);
                        }
                        return;
                    }
                    RxBus.get().postEvent(Constants.Event.Refresh_Video_List);

                    List<MultiItemWrapper> list = new ArrayList<>();
                    if (CollectionHelper.isNotEmpty(respBean.getData())) {
                        for (VideoListBean videoListBean : respBean.getData()) {
                            list.add(MultiItemWrapper.of(NORMAL_VIDEO, videoListBean));
                        }
                    }

                    mCurSelectPage = -1;
                    solvePagesData(list, page, Constants.PAGE_SIZE);
                }, RxHelper.getSwitchableErrorConsumer(this)));
    }
}
